import os, sys, atexit

#from django.utils.daemonize import become_daemon
from jobs.daemonize import become_daemon
from django.core.management.base import BaseCommand

from jobs.models import Daemon, Job

from django.conf import settings

import time
class DBDevice:
  def __init__(self, method):
    self.method = method
    self.buf = ''
    self.t = time.time()
    self.r, self.w = os.pipe()
    
  def write(self, s):
    if settings.DEBUG:
      self.method(self.buf)
    else:
      self.buf += s
      if (time.time() - self.t > 1): # Save the log once every second max
        self.method(self.buf)
        self.buf = ''
        self.t = time.time()
    
  def __del__(self):
    self.close()
  def close(self):
    self.method(self.buf)
  def fileno(self):
    return self.w

class JobDaemon(Daemon):
  class Meta:
    proxy = True

  @staticmethod
  def Create(id):
    d, created = JobDaemon.objects.get_or_create(id=id)
    print "JobDaemon::Create", created, id
    d.command = str(JobDaemon.__name__.lower())
    d.save()
    return d
    
  def daemonize(self):
    sys.stdout.flush()
    sys.stderr.flush()    
    
    #TODO: direct to DB, this doesnt seem to be working well yet :(
    #stdout = DBDevice(self.append_stdout)
    #stderr = DBDevice(self.append_stderr)
    #become_daemon(our_home_dir="/", stdout=stdout, stderr=stderr)
    
    cdir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../..')
    become_daemon(our_home_dir="/", stdout=open(os.path.join(cdir, 'out.log'), 'a+', 0), stderr=open(os.path.join(cdir, 'err.log'), 'a+', 0))
    
    import logging
    from jobs.models import LOG
    ch = logging.StreamHandler(sys.stdout)
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    ch.setFormatter(formatter)
    
    LOG.addHandler(ch)
    LOG.setLevel(logging.INFO)

    atexit.register(self._resetpid)
    self._setpid()

  def run(self):
    Job.objects._run(self.workers)


from optparse import make_option

class Command(BaseCommand):
  option_list = BaseCommand.option_list + (
        make_option('-i', '--id', action="store", type="int", dest="id", default=1),
        )

  def handle(self, *args, **options):
    if len(args) == 1 and args[0] in ['start', 'stop', 'restart']:
          
      daemon = JobDaemon.Create(options.get('id', 1))
      getattr(daemon, args[0])()
    else:
      return "Usage: %s %s start|stop|restart|run\n" % (sys.argv[0], sys.argv[1])

